import {Component, OnInit} from '@angular/core';
import {ActivatedRoute, ParamMap} from '@angular/router';
import {switchMap} from 'rxjs/operators';
import {UserService} from '../user.service';
import {UserShow} from './show.modle';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Location} from '@angular/common';


@Component({
    selector: 'app-show',
    templateUrl: './show.component.html',
})
export class ShowComponent implements OnInit {

    userinfo: UserShow = {
        id: 0,
        username: '',
        head: '',
        nickname: '',
        sex: 0,
        email: '',
        address: '',
    };

    validateForm: FormGroup;

    constructor(
        private route: ActivatedRoute,
        private userService: UserService,
        private fb: FormBuilder,
        private location: Location,
    ) {
        this.validateForm = this.fb.group({
            id: ['0'],
            nickname: [''],
            headimg: [''],
            email: ['', Validators.email],
            address: [''],
            sex: [0],
        });
    }

    ngOnInit() {


        this.route.paramMap.pipe(
            switchMap((params: ParamMap) =>
                this.userService.showuser(+params.get('id'))
            )
        ).subscribe(res => {
            this.userinfo = res;
            this.userinfo.head = res['headimg'];

            this.validateForm.patchValue({
                id: this.userinfo.id,
                headimg: this.userinfo.head,
                nickname: this.userinfo.nickname,
                email: this.userinfo.email,
                address: this.userinfo.address,
                sex: this.userinfo.sex,
            });
            // console.error('-----get userinfo' + res);
        });
    }

    update() {
        const res = this.validateForm.value;
        this.userinfo.id = res['id'];
        this.userinfo.nickname = res['nickname'];
        this.userinfo.head = res['headimg'];
        this.userinfo.email = res['email'];
        this.userinfo.address = res['address'];
        this.userinfo.sex = res['sex'];

        this.userService.updateinfo(this.userinfo).subscribe((r) => {
            this.location.back();
        });
    }

    cancel() {
        this.location.back();
    }
}
